package com.pithypan.controller;


import com.pithypan.common.Constants;
import com.pithypan.common.FileCategoryEnums;
import com.pithypan.common.utils.R;
import com.pithypan.common.utils.RedisUtils;
import com.pithypan.common.utils.StringTools;
import com.pithypan.convert.UserInfoConvert;
import com.pithypan.dto.SessionWebUserDto;
import com.pithypan.dto.SysSettingsDto;
import com.pithypan.service.FileInfoService;
import com.pithypan.service.UserInfoService;
import com.pithypan.vo.FileInfoQuery;
import com.pithypan.vo.PaginationResultVo;
import com.pithypan.vo.UserInfoQuery;
import com.pithypan.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * 管理员
 */
@RestController
@RequestMapping("/admin")
public class AdminController extends CommonFileController {

    @Resource
    private FileInfoService fileInfoService;
    @Resource
    private UserInfoService userInfoService;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 获取系统设置
     * @return
     */
    @RequestMapping("/getSysSettings")
    public R getSysSettings() {
        //先从redis缓存中获取模板
        SysSettingsDto sysSettingsDto = (SysSettingsDto) redisUtils.get(Constants.REDIS_KEY_SYS_SETTING);
        //缓存中没有，则根据默认模版创建一封邮件并存入redis中
        if (sysSettingsDto == null) {
            sysSettingsDto = new SysSettingsDto();
            redisUtils.set(Constants.REDIS_KEY_SYS_SETTING, sysSettingsDto);
        }
        return R.ok().data("sysSettingsDto", sysSettingsDto);
    }


    /**
     * 修改系统设置
     * @param registerEmailTitle     邮件标题
     * @param registerEmailContent   邮件内容
     * @param userInitUserSpace      占用空间
     * @return
     */
    @RequestMapping("/saveSysSettings")
    public R saveSysSettings(String registerEmailTitle, String registerEmailContent, Integer userInitUserSpace) {
        SysSettingsDto sysSettingsDto = new SysSettingsDto();
        sysSettingsDto.setRegisterEmailTitle(registerEmailTitle);
        sysSettingsDto.setRegisterEmailContent(registerEmailContent);
        sysSettingsDto.setUserInitUserSpace(userInitUserSpace);
        redisUtils.set(Constants.REDIS_KEY_SYS_SETTING, sysSettingsDto);
        return R.ok();
    }


    /**
     * 分页查询用户列表
     * @param query
     * @return
     */
    @RequestMapping("/loadUserList")
    public R loadUserList(@RequestBody UserInfoQuery query) {
        query.setOrderBy("join_time desc");

        PaginationResultVo resultVo = userInfoService.findListByPage(query);
        List<UserInfoVo> listVO = UserInfoConvert.INSTANCE.listentity2vo(resultVo.getList()); //转换
        resultVo.setList(listVO);
        return R.ok().data("userList", resultVo);
    }


    /**
     * 用户状态修改 启用/禁用
     * @param userId
     * @param status
     * @return
     */
    @RequestMapping("/updateUserStatus")
    public R updateUserStatus(String userId, Integer status) {
        userInfoService.updateUserStatus(userId, status);
        return R.ok();
    }


    /**
     * 修改用户可使用总空间
     * @param userId
     * @param changeSpace
     * @return
     */
    @RequestMapping("/changeUserSpace")
    public R changeUserSpace(String userId, Long changeSpace) {
        userInfoService.changeUserSpace(userId, changeSpace);
        return R.ok();
    }


    /**
     * 文件列表分页查询，且关联user表查询用户名
     * @param query
     * @return
     */
    @RequestMapping("/loadFileList")
    public R loadDataList(@RequestBody FileInfoQuery query) {
        if (query.getFileNameFuzzy() == null) {
            System.out.println("111");
        }
        query.setOrderBy("last_update_time desc");       //根据更新时间降序排序
        query.setQueryNickName(true);
        PaginationResultVo result = fileInfoService.findFileAndNickName(query);
        return R.ok().data("fileList", result);
    }


    /**
     * 根据 id串 获取相对应的目录
     * @param path       路径, id串用 / 字符分隔（例：wuvakndsa/aknababa）
     * @return
     */
    @RequestMapping("/getFolderInfo")
    public R getFolderInfo(String path) {
        return super.getFolderInfo(null, path);
    }


    /**
     * 视频文件分段预览
     * @param response
     * @param userId
     * @param fileId  视频文件id 或 视频分片名称（如：QZeD5BDF9w_0000.ts）
     */
    @RequestMapping("/ts/getVideoInfo/{userId}/{fileId}")
    public void getVideo(HttpServletResponse response, @PathVariable("userId") String userId, @PathVariable("fileId") String fileId) {
        super.getFile(response, fileId, userId);
    }


    /**
     * 其它文件 预览
     * @param response
     * @param fileId
     */
    @RequestMapping("/getFile/{userId}/{fileId}")
    public void getFile(HttpServletResponse response, @PathVariable("userId") String userId, @PathVariable("fileId") String fileId) {
        super.getFile(response, fileId, userId);
    }


    /**
     * 创建下载
     * @param fileId 需下载的文件
     * @return
     */
    @RequestMapping("/createDownloadUrl/{userId}/{fileId}")
    public R createDownloadUrl(@PathVariable("userId") String userId, @PathVariable("fileId") String fileId) {
        return super.createDownloadUrl(userId, fileId);
    }


    /**
     * 文件下载
     * @param request
     * @param response
     * @param code
     * @throws Exception
     */
    @RequestMapping("/download/{code}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception {
        super.download(request, response, code);
    }


    /**
     * 删除文件（从数据库中删除）
     * @param session
     * @param userIdAndFileIds  用户名_文件名，用户名_文件名...
     * @return
     */
    @RequestMapping("/delFile")
    public R delFile(HttpSession session, String userIdAndFileIds) {
        String[] userIdAndFileIdArray = userIdAndFileIds.split(",");
        for (String userIdAndFileId : userIdAndFileIdArray) {
            String[] itemArray = userIdAndFileId.split("_");
            fileInfoService.delFileBatch(itemArray[0], itemArray[1], true);
        }
        return R.ok();
    }

}
